﻿if(!localStorage.getItem('loginUser') && location.href.indexOf('login.html')<0)
    location.href='login.html';

var apiUrl = 'http://193.112.66.118:6600';
var icmpApi='http://193.112.66.118:8081/appApi';
var a = 'app_icm,c53fba02-f505-4e9f-95b6-ae8c0025206e';
$.cookie('reqConfItem', a);
localStorage.setItem('reqConfItem', a);

//语言设置
var language = $.cookie("lan");
if (!language)
    language = 'zh';
translate(language);
$("#_languageList li").removeClass("li-active");
$("#_languageList li").each(function (i, e) {
    if ($(e).attr('user-val') == language)
        $(e).addClass('li-active');
});

   
//语言栏
$("#_languageBtn").mouseover(function () {
    $("#_languageList").slideDown();
});
$("#_languageList").mouseleave(function(){
    $("#_languageList").slideUp();
});
$("#_languageList li").click(function () {
    $('#_languageBtn').html($(this).text() + '<img src="asset/image/icon_pull_down.png"/>');
    var _language = $(this).attr("user-val");
    if (translate(_language)) {
        $("#_languageList li").removeClass("li-active");
        $(this).addClass("li-active");
        //刷新数据语言
        var _content = $.cookie('sysInfo');
        if (_content) {
            var _data = JSON.parse(_content);
            var userCookie = $.cookie("user");
            var b = new Base64();
            var decryptCookie = b.decode(userCookie);
            var jsonCookie = JSON.parse(decryptCookie);
            var _html = '';
            for (var i = 0; i < _data.length; i++) {
                var _sysName = '';
                switch (language) {
                    case 'zh':
                        _sysName = _data[i].sys_namec;
                        break;
                    case 'zf':
                        _sysName = _data[i].sys_namec;
                        break;
                    case 'en':
                        _sysName = _data[i].sys_namee;
                        break;
                }
                _html += '<div class="col-md-3 sysArea" onclick="Go(\'' + _data[i].sys_url + '\',\'' + jsonCookie.userNo + '\',\'' + jsonCookie.timeStamp + '\',\'' + _data[i].sys_code + '\')">';
                if (_data[i].pic_logo)
                    _html += '<img class="img-responsive" src="' + _data[i].pic_logo + '" />';
                else
                    _html += '<img class="img-responsive" src="asset/image/noPhoto.png" />';
                _html += '<label>' + _sysName + '</label>';
                _html += '</div>';
            }
            $("#_chooseSystem").html(_html);
        }
    } 
});


//提示框
function niceAlert(_level, _c, _v) {
    switch (_level) {
        case 1:
            $(".alert").addClass('alert-warning');
            break;
        case 2:
            $(".alert").addClass('alert-danger');
            break;
        default:
            $(".alert").addClass('alert-info');
            break;
    }
    $.ajax({
        url: 'asset/jsonData/language/' + language + '.json',
        dataType: 'json',
        type: 'get',
        success: function (r) {
            var _msg = r[_c];
            if (!_msg)
                _msg = _c;
            if (_msg.indexOf('{0}'))
                _msg = _msg.replace('{0}',_v);
            $("#_c").html(_msg);
            $(".alert").slideDown(200);
            var timer = setTimeout(function () {
                closeAlert();
                clearTimeout(timer);
            }, 3 * 1000);
        }
    });
}

function showTips(_c, _v) {
    $.ajax({
        url: 'asset/jsonData/language/' + language + '.json',
        dataType: 'json',
        type: 'get',
        success: function (r) {
            var _msg = r[_c];
            if (!_msg)
                _msg = _c;
            if (_msg.indexOf('{0}'))
                _msg = _msg.replace('{0}', _v);
            $("#_tips").html(_msg).show();
            
            var timer = setTimeout(function () {
                $("#_tips").hide();
                clearTimeout(timer);
            }, 3 * 1000);
        }
    });
}

function closeAlert() {
    $(".alert").slideUp(200);
}

//翻译
function translate(_language) {
    var languageArray = new Array('zh', 'zf', 'en');//0：简体中文；1：繁体中文；2：英文
    if ($.inArray(_language, languageArray) < 0)
        return false;
    //to do translate things
    var expDate = new Date();
    expDate.setTime(expDate.getTime() + (30 * 24 * 60 * 60 * 1000)); // add 30 days
    switch (_language) {
        case 'zh':
            //translate to simple Chinese
            $('#_logo').attr('src', 'asset/image/logo_zh.png');
            $('#_languageBtn').html('简体中文<img src="asset/image/icon_pull_down.png"/>');
            language = 'zh';
            requestLanguageData('zh');
            $.cookie("lan", 'zh', { expires: expDate });
            break;
        case 'zf':
            //translate to traditional Chinese
            $('#_logo').attr('src', 'asset/image/logo_zf.png');
            $('#_languageBtn').html('繁體中文<img src="asset/image/icon_pull_down.png"/>');
            language = 'zf';
            requestLanguageData('zf');
            $.cookie("lan", 'zf', { expires: expDate });
            break;
        case 'en':
            //translate to English
            $('#_logo').attr('src', 'asset/image/logo_en.png');
            $('#_languageBtn').html('English<img src="asset/image/icon_pull_down.png"/>');
            language = 'en';
            requestLanguageData('en');
            $.cookie("lan", 'en', { expires: expDate });
            break;
    }
    return true;
}

//获取语言包并翻译页面
function requestLanguageData(_language) {
    $.ajax({
        url: 'asset/jsonData/language/' + _language + '.json',
        dataType: 'json',
        type: 'get',
        success: function (r) {
            $("[user-lan]").each(function (i, e) {
                var keyName = $.trim($(e).attr("user-lan"));
                if (keyName && keyName.indexOf('[') >= 0 && keyName.indexOf(']') >= 0) {
                    //console.log(i+': html='+$(e).html() + '   val=' + $(e).val() + '   pl=' + $(e).attr("placeholder"));
                    $(e).html(r[keyName]);
                    //$(e).val(r[keyName]);
                    $(e).attr("placeholder", r[keyName]);
                }
            });
        }
    });
}

//生成签名
function createSign(jsonData) {
    var _arr = $.cookie('reqConfItem').split(',');
    if (_arr.length !== 2) {
        niceAlert(2, '[serverError]');
        return;
    }
    var _appKey = _arr[1];
    var keyArray = new Array();
    for (var key in jsonData) {
        if (key == 'sign')
            continue;
        keyArray.push(key);
    }
    keyArray.sort();//正序sort() 反序reverse()
    var signStr = '';
    //console.log('jsonData',jsonData);
    for (let i = 0; i < keyArray.length; i++) {
        if(jsonData[keyArray[i]] != null && jsonData[keyArray[i]] !== undefined){
            if(this.isArray(jsonData[keyArray[i]]))
                signStr += (keyArray[i] + '=' + JSON.stringify(jsonData[keyArray[i]]) + '&').replace(/"/g, '').replace(/'/g, '');
            else if(jsonData[keyArray[i]].toString() !== '')
                signStr += keyArray[i] + '=' + jsonData[keyArray[i]] + '&';
        }
    }
    signStr += 'key=' + _appKey;
    console.log('signStr',signStr);
    var urlEncodeSign = encodeURIComponent(signStr).toUpperCase();
    //console.log('urlEncodeSign',urlEncodeSign);
    var sign = hex_sha1(urlEncodeSign);
    console.log('sign',sign);
    return sign;
}

function isArray(o) {
    var type = Object.prototype.toString.call(o);
    if (type == '[object Object]' || type == '[object Array]')
        return true;
    else
        return false
}

var b = new Base64();
var arr = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "J", "I", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];

function insertStr(source, start, inStr) {
    return source.slice(0, start) + inStr + source.slice(start);
}

function generateRandom(count, index) {
    var returnStr = "";
    while (count != 0) {
        returnStr += arr[Math.round(Math.random() * index)];
        count--;
    }
    return returnStr;
}

function decodeAndMixStr(str, code) {
    if (code == 1) {
        str = insertStr(insertStr(str, 1, generateRandom(2, 9)), 7, generateRandom(3, 9));
    } else if (code == 2) {
        str = insertStr(insertStr(str, 1, generateRandom(2, arr.length - 1)), 7, generateRandom(3, arr.length - 1));
    }
    return b.encode(str);
}